package com.pomr.service.sys.Impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pomr.model.health.FriendTel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pomr.dao.sys.PersonRecordDao;
import com.pomr.model.form.RecordSelect;
import com.pomr.model.health.FamilyRelation;
import com.pomr.model.health.PersonRecord;
import com.pomr.model.sys.User;
import com.pomr.service.sys.PersonRecordService;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.page.Page;
/**
 * 个人档案
 * @author Administrator
 *
 */
@Service
public class PersonRecordServiceImpl implements PersonRecordService {
	@Autowired
	@Qualifier("personRecordDaoImpl")
	private PersonRecordDao personRecordDao;

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean insertRecord(PersonRecord record) throws Exception {
		if(record.getChild()==1){//如果是新生儿 使用父母身份证号 后跟1XX
			String hql = "from PersonRecord where idcard like '"+record.getIdcard()+"%' and idcard != '"+record.getIdcard()+"' order by idcard desc";
			List<PersonRecord> res = personRecordDao.findByHqlNoCache(hql);
			if(res!=null && res.size()>0){
				String card = res.get(0).getIdcard();
				int num = Integer.valueOf(card.substring(card.length()-3));
				record.setIdcard(record.getIdcard()+(num+1));
			}else{
				record.setIdcard(record.getIdcard()+"101");
			}
		}
		return personRecordDao.add(record);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean deleteRecord(PersonRecord record) throws Exception {
		//先更新家庭关系，如果为户主1.选择其他成员为户主2.直接删除家庭档案
		String hql = "from FamilyRelation where personrecord.id="+record.getId();
		List<FamilyRelation> fam = personRecordDao.findByHql(hql);
		if(fam!=null){
			hql = "from FamilyRelation where familyrecord_id="+fam.get(0).getFamilyrecord_id();
			List<FamilyRelation> fams = personRecordDao.findByHql(hql);
			if(fams!=null){
				if(fams.size()==1){//家庭只有一个成员 直接删除全部家庭档案
					if(!personRecordDao.editHql("delete from FamilyRelation where personrecord.id="+record.getId())){
						throw new Exception("删除家庭关系失败");
					}
					if(!personRecordDao.editHql("delete from FamilyRecord where id="+fam.get(0).getFamilyrecord_id())){
						throw new Exception("删除家庭关系失败");
					}
				}else{//有多个家庭成员 随机选择一个设为户主
					//判断是户主
					if(fam.get(0).getRelation().getId()==1){
						for(FamilyRelation f:fams){
							if(record.getId()!=f.getPersonrecord().getId()){
								if(!personRecordDao.editHql("delete from FamilyRelation where personrecord.id="+record.getId())){
									throw new Exception("删除家庭关系失败");
								}
								if(!personRecordDao.editHql("update FamilyRelation set relation.id=1 where id="+f.getId())){
									throw new Exception("删除家庭关系失败");
								}
								break;
							}
						}
					}else{
						//不是户主
						if(!personRecordDao.editHql("delete from FamilyRelation where id="+fam.get(0).getId())){
							throw new Exception("删除家庭关系失败");
						}
					}
					
				}
			}
		}
		//删除个人档案
		if(record.getId() > 0){
			if(!personRecordDao.editHql("delete from PersonRecord where id="+record.getId())){
				throw new Exception("删除个人档案失败");
			}
		}else{//通过身份证号删除
			if(!personRecordDao.editHql("delete from PersonRecord where idcard = '"+record.getIdcard()+"'"))
				throw new Exception("删除个人档案失败");
		}
		return true;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean updateRecord(PersonRecord record) throws Exception {
		if(record.getId() > 0){
			return personRecordDao.editEntity(record);
		}else{//通过身份证号更新
			String hql = record.getUpdateHql();
			if(hql==null || "".equals(hql)){
				return false;
			}
			return personRecordDao.editHql("update PersonRecord set "+hql+" where idcard ='"+record.getIdcard()+"'");
		}
	}
	
	/**
	 * 根据条件查询
	 * @return
	 * @throws Exception
	 */
	public Page<List<PersonRecord>> selectRecords(RecordSelect select,Page<List<PersonRecord>> page) throws Exception{
		StringBuilder hql = new StringBuilder();
		hql.append(" where 1=1 ");
		int i = 1;
		Map<String, Object> params = new HashMap<String, Object>();
		if(select.getName() != null && !"".equals(select.getName())){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.name like '%"+select.getName()+"%'");
			i++;
		}
		if(select.getIdcard() != null && !"".equals(select.getIdcard())){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.idcard = "+select.getIdcard());
			i++;
		}
		if(select.getStatus() != null && !"".equals(select.getStatus())){
			if(i>0){
				hql.append(" and ");
			}
			if("0".equals(select.getStatus())){//全部
				hql.append(" 1 = 1 ");
			}else if("1".equals(select.getStatus())){//正常
				hql.append("(pp.status != '1' or pp.status = null)");
			}else if("2".equals(select.getStatus())){//停用
				hql.append("(pp.status = '1')");
			}else{//默认正常
				hql.append("(pp.status != '1' or pp.status = null)");
			}
			i++;
		}
		if(select.getCreateTime1() != null){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.createTime >= :startTime");
			params.put("startTime", select.getCreateTime1());
			i++;
		}
		if(select.getCreateTime2() != null){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.createTime <= :endTime");
			params.put("endTime", select.getCreateTime2());
			i++;
		}
		if(select.getAgencyId()>0){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.agency.id = "+select.getAgencyId());
			i++;
		}
		if(select.getHealthConditionId()>0){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.healthCondition.id = "+select.getHealthConditionId());
			i++;
		}
		if(select.getSexId()>0){
			if(i>0){
				hql.append(" and ");
			}
			hql.append("pp.sex.id = "+select.getSexId());
			i++;
		}
		
		String str1 = "from PersonRecord pp left join fetch pp.province left join fetch pp.city left join fetch pp.coutry "+hql.toString();
		String str2 = "from PersonRecord pp "+hql.toString();
		page = personRecordDao.showPageParam(str1, "select count(1) "+str2, page, params);//根据条件组配hql
		return page;
	}

	@Override
	public PersonRecord selectRecord(PersonRecord record) throws Exception {
		String hql = "from PersonRecord p left join fetch p.sex left join fetch p.coutry "+
				"left join fetch p.industry "+
				"left join fetch p.marriage "+
				"left join fetch p.user "+
				"left join fetch p.agency "+
				"left join fetch p.healthCondition "+
				"where ";
		if(record.getId()>0){
			hql += "p.id="+record.getId();
		}else if(!record.getIdcard().equals("") && !record.getIdcard().equals("null")){
			hql += "p.idcard="+record.getIdcard();
		}
		List<PersonRecord> records = personRecordDao.findByHql(hql);
		if(records!=null && records.size()>0){
			return records.get(0);
		}
		return null;
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public boolean deleteRecords(List<String> ids) throws Exception {
		if(ids==null || ids.size()<=0){
			return false;
		}
		String idstr = StringUtils.join(ids.iterator(), ',');
		String delsql = "delete from Person_Record where id in ("+idstr+")";
		return personRecordDao.remove(delsql);
	}

	@Transactional(rollbackFor=Exception.class)
	@Override
	public boolean updateRecords(List<PersonRecord> records) throws Exception {
		int len = records.size();
		PersonRecord record = null;
		boolean succ = true;
		for(int i=0;i<len;i++){
			record = records.get(i);
			if(record.getId()<=0 && (record.getIdcard()==null || "".equals(record.getIdcard()))){//如果主键跟身份证号都不存在，无法删除
				throw new Exception("没有可用的主键或身份证号");
			}
			if(record.getId() > 0){
				succ = personRecordDao.editEntity(record);
			}else{//通过身份证号更新
				String hql = record.getUpdateHql();
				if(hql==null || "".equals(hql)){
					throw new Exception("更新语句错误");
				}
				succ = personRecordDao.editHql("update PersonRecord set "+hql+" where idcard ='"+record.getIdcard()+"'");
			}
			if(!succ){
				throw new Exception("更新失败："+record.getIdcard()+","+record.getIdcard());
			}
		}
		return true;
	}

	@Override
	public Page<PersonRecord> selectByConditions() throws Exception {
		Page<PersonRecord> p = new Page<PersonRecord>();
		p.setCunrrentPage(1);
		p.setPageSize(10);
		p = personRecordDao.showPage("from PersonRecord", "select count(1) from PersonRecord", p);
		return p;
	}

	@Override
	public boolean searchPersonRecordByIdcard(String idcard) throws Exception {
		List<PersonRecord> prs = personRecordDao.findByHql("from PersonRecord where idcard ='"+idcard+"'");
		if(prs==null || prs.size()<=0){
			return false;
		}
		return true;
	}

	@Override
	public boolean editRecord(PersonRecord record) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("update PersonRecord set ");
		sb.append("name = '"+record.getName()+"', ");
		sb.append("idcard = '"+(record.getIdcard()==null?"":record.getIdcard())+"', ");
		if(record.getSex()!=null){
			sb.append("sex.id = "+record.getSex().getId()+", ");
		}
		
		sb.append("tel = '"+(record.getTel()==null?"":record.getTel())+"', ");
		if(record.getIndustry()!=null){
			sb.append("industry.id = "+record.getIndustry().getId()+", ");
		}
		if(record.getMarriage()!=null){
			sb.append("marriage.id = "+record.getMarriage().getId()+", ");
		}
		if(record.getHealthCondition()!=null){
			sb.append("healthCondition.id = "+record.getHealthCondition().getId()+", ");
		}
		if(record.getProvince()!=null){
			sb.append("province.id = "+record.getProvince().getId()+", ");
		}
		if(record.getCity()!=null){
			sb.append("city.id = "+record.getCity().getId()+", ");
		}
		if(record.getCoutry()!=null){
			sb.append("coutry.id = "+record.getCoutry().getId()+", ");
		}
		sb.append("addr = '"+(record.getAddr()==null?"":record.getAddr())+"', ");
		sb.append("status = "+record.getStatus()+" ");
		sb.append("where id = "+record.getId());
		System.out.println(sb.toString());
		return personRecordDao.editHql(sb.toString());
	}

	@Override
	public List<PersonRecord> searchRecords(String tj, User user) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append("from PersonRecord where ");
		sb.append("name like '%"+tj+"%' or ");
		sb.append("idcard like '%"+tj+"%' ");
		if(user.getRole().getType() == 1){//超级管理员
			
		}else{
			sb.append(" and agency.id = "+user.getAgency().getId());
		}
		sb.append(" and id not in (");
		sb.append("select fr.personrecord.id from FamilyRelation fr)");
		return personRecordDao.findByHql(sb.toString());
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean editRecordStatus(PersonRecord record) throws Exception {
		String hql = "update PersonRecord set status = '"+record.getStatus()+"' where id="+record.getId();
		return personRecordDao.editHql(hql);
	}

	@Override
	public Page<List<PersonRecord>> selectRecordsByConds(String limit, String page, String conds) throws Exception {
		String hql = "from PersonRecord where (idcard like '%"+conds+"%' or name like '%"+conds+"%' )"
				+ "and id not in (select personrecord.id from FamilyRelation)";
		Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
		p.setCunrrentPage(Integer.valueOf(page==null?"1":page));
		p.setPageSize(Integer.valueOf(limit));
		p = personRecordDao.showPage(hql, "select count(1) "+hql, p);//根据条件组配hql
		return p;
	}

	@Override
	public Page<List<PersonRecord>> selectRecordsByCondsOfFam(String limit, String page, String conds)
			throws Exception {
		String hql = "from PersonRecord where (idcard like '%"+conds+"%' or name like '%"+conds+"%' )"
				+ "and id in (select personrecord.id from FamilyRelation)";
		Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
		p.setCunrrentPage(Integer.valueOf(page==null?"1":page));
		p.setPageSize(Integer.valueOf(limit));
		p = personRecordDao.showPage(hql, "select count(1) "+hql, p);//根据条件组配hql
		return p;
	}

	@Override
	public Page<List<PersonRecord>> searchUsersOfReceive(String page, String limit, String idcard) throws Exception {
		//未死亡的正常的健康档案
		String hql = "from PersonRecord where idcard like '%"+idcard+"%' and (status!=1 or status=null) and (healthCondition.id!=5 or healthCondition.id = null)";
		Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
		p.setCunrrentPage(Integer.valueOf(page==null?"1":page));
		p.setPageSize(Integer.valueOf(limit));
		return personRecordDao.showPage(hql, "select count(1) "+hql, p);//根据条件组配hql
	}


	@Override
	public List<PersonRecord> searchUsersOfReceive(String keywords) throws Exception {
		//未死亡的正常的健康档案
		String hql = "from PersonRecord where idcard like '%"+keywords+"%' and (status!=1 or status=null) and (healthCondition.id!=5 or healthCondition.id = null)";
		Page<List<PersonRecord>> p = new Page<List<PersonRecord>>();
		p.setCunrrentPage(1);
		p.setPageSize(5);
		Page<List<PersonRecord>> data = personRecordDao.showPage(hql, "select count(1) "+hql, p);//根据条件组配hql
		return data.getRows();
	}

	@Override
	public ResponseData searchFriendTel(String recordid) throws Exception {
		if(StringUtils.isEmpty(recordid)){
			return ResponseData.custom("健康档案信息未上传");
		}
		String hql = "from FriendTel where recordId="+recordid;
		List<FriendTel> friendTels = personRecordDao.findByHql(hql);
		return ResponseData.ok().putDataValue("ftel", friendTels);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseData addFriendTel(FriendTel friendTel) throws Exception {
		if(friendTel.getRecordId()==null || friendTel.getRecordId()<=0){
			return ResponseData.custom("健康档案信息未上传");
		}
		String fid = null;
		if(StringUtils.isEmpty(fid = personRecordDao.addStringKey(friendTel))){
			throw new Exception("保存亲友信息失败");
		}
		return ResponseData.ok().putDataValue("fid",fid);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public ResponseData deleteFriendTel(FriendTel friendTel) throws Exception {
		if(StringUtils.isEmpty(friendTel.getId())){
			return ResponseData.custom("亲友信息未上传");
		}
		friendTel = personRecordDao.getById(FriendTel.class, friendTel.getId());
		if(!personRecordDao.removeEntity(friendTel)){
			throw new Exception("删除亲友信息失败");
		}
		return ResponseData.ok();
	}

	@Override
	public ResponseData searchFriendTelApp(String idcard) throws Exception {
		if(StringUtils.isEmpty(idcard)){
			return ResponseData.custom("身份证号未上传");
		}
		String hql = "from FriendTel ft where ft.recordId=(select distinct pr.id from PersonRecord pr where pr.idcard='"+idcard+"')";
		List<FriendTel> friendTels = personRecordDao.findByHql(hql);
		return ResponseData.ok().putDataValue("friendTels", friendTels);
	}
}
